import {createRouter, createWebHashHistory} from 'vue-router'
import {useUserStore} from "@/stores/index.js";

const routes = [
  {path: '/login', component: () => import('@/views/login/LoginPage.vue')},
  {path: '/register', component: () => import('@/views/login/RegisterPage.vue')},
  {
    path: '/',
    component: () => import('@/views/layout/IndexPage.vue'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: () => import('@/views/layout/HomePage.vue'),
      },
      {
        path: '/team',
        component: () => import('@/views/layout/TeamPage.vue'),
      },
      {
        path: '/user',
        component: () => import('@/views/layout/UserPage.vue'),
        meta: {requiresAuth: true}
      },
      {
        path: '/find',
        component: () => import('@/views/layout/FindPage.vue'),
      }
    ]
  },
  {path: '/set', component: () => import('@/views/set/SetPage.vue'), meta: {requiresAuth: true}},
  {path: '/info', component: () => import('@/views/set/InfoSetPage.vue'), meta: {requiresAuth: true}},
  {path: '/tag', component: () => import('@/views/tag/TagPage.vue'), meta: {requiresAuth: true}},
  {path: '/tag/add', component: () => import('@/views/tag/AddTagPage.vue'), meta: {requiresAuth: true}},
  {path: '/tag/search', component: () => import('@/views/search/TagSearchPage.vue'), meta: {requiresAuth: true}},
  {path: '/user/detail/:id', component: () => import('@/views/user/UserDetailPage.vue'), meta: {requiresAuth: true}},
  {path: '/team/detail/:id', component: () => import('@/views/team/TeamDetailPage.vue'), meta: {requiresAuth: true}},
  {path: '/team/add', component: () => import('@/views/team/AddTeamPage.vue'), meta: {requiresAuth: true}},
  {path: '/team/tag', component: () => import('@/views/team/AddTagPage.vue'), meta: {requiresAuth: true}},
]

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: routes
})

router.beforeEach((to, from, next) => {
  // 检查是否需要进行认证
  const userStore = useUserStore();

  // 如果不需要认证, 则继续导航
  if (!to.matched.some(record => record.meta.requiresAuth)) {
    return next(); // 使用 return 确保只调用一次 next
  }

  // 检查是否存在 JWT 令牌
  if (!userStore.token) {
    // eslint-disable-next-line no-undef
    showToast('请先登录')
    // 如果没有 JWT 令牌, 则跳转到登录页面
    return next('/login'); // 使用 return 确保只调用一次 next
  }

  // 如果有 JWT 令牌, 则继续导航
  next(); // 只有在上述条件都不满足时才会到达这里
});

export default router
